package servlet;

import entity.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.commons.codec.digest.DigestUtils;
import service.UserDaoService;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        HttpSession session=request.getSession();
        UserDaoService checkLogin = new UserDaoService();
        User u = new User();
        String email = request.getParameter("userName");
        String upass = request.getParameter("passWord");
        String MD5pass = DigestUtils.md5Hex(upass);
        User user = checkLogin.Login(email, MD5pass);
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("当前时间：" + sdf.format(d));
        if (user != null) {
            u.setUid(user.getUid());
            u.setUsername(user.getUsername());
            u.setEmail(email);
            session.setAttribute("nowTime",sdf.format(d));
            session.setAttribute("login",u);
            response.sendRedirect("./WinterTourism/material/NewsShow.jsp");
        }else {
            out.print("<script language='javascript'>alert('账号或密码错误!'); window.location.href='./WinterTourism/material/login.jsp'; </script>");
        }
    }
}
